<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import "vue-json-pretty/lib/styles.css";
import VueJsonPretty from "vue-json-pretty";
import { JSONDataType } from "vue-json-pretty/types/utils";
import { ElMessage } from "element-plus";

defineOptions({
  name: "JsonEditor"
});
const state = reactive({
  showLine: true,
  showLineNumber: true,
  showDoubleQuotes: true,
  showLength: true,
  editable: true,
  showIcon: true,
  editableTrigger: "click",
  deep: 3,
  visible: false
});

const props = defineProps({
  json: {}
});
const jsonData = ref<JSONDataType>(props.json as JSONDataType);
watch(
  () => state.visible,
  () => {
    jsonData.value = props.json as JSONDataType;
  }
);
const emits = defineEmits(["update:json"]);

function handleConfirm() {
  emits("update:json", jsonData.value);
  state.visible = false;
}

async function handleCopy() {
  try {
    if (navigator.clipboard) {
      // 将 JSON 对象转换为字符串
      const jsonString = JSON.stringify(jsonData.value, null, 2);
      await navigator.clipboard.writeText(jsonString); // 写入剪切板
      ElMessage.success("复制成功");
      console.log("内容已复制到剪切板");
    } else {
      console.error("浏览器不支持 Clipboard API");
    }
  } catch (err) {
    console.error("复制失败:", err);
  }
}

const jsonDataString = computed({
  get: () => JSON.stringify(jsonData.value, null, 2),
  set: value => {
    try {
      jsonData.value = JSON.parse(value); // 解析字符串为 JSON 对象
    } catch (error) {
      ElMessage.error("输入的内容不是有效的 JSON 格式");
    }
  }
});
</script>

<template>
  <el-button @click="state.visible = true">点击查看</el-button>
  <ElDrawer
    v-model="state.visible"
    title="编辑json"
    cancel-text="取消"
    confirm-text="确定"
    size="60%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <el-row>
      <el-col :span="12">
        <vue-json-pretty
          v-model:data="jsonData"
          :deep="state.deep"
          :show-double-quotes="state.showDoubleQuotes"
          :show-line="state.showLine"
          :show-length="state.showLength"
          :show-icon="state.showIcon"
          :show-line-number="state.showLineNumber"
          :editable="state.editable"
        />
      </el-col>
      <el-col :span="10" :offset="1">
        <el-input v-model="jsonDataString" type="textarea" autosize />
      </el-col>
    </el-row>

    <template #footer>
      <el-button type="primary" @click="handleCopy">点击复制</el-button>
      <el-button type="success" @click="handleConfirm">点击保存</el-button>
    </template>
  </ElDrawer>
</template>
